package tech.xs.auth.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.xs.auth.domain.bo.auth.AuthUserJurisdictionBo;
import tech.xs.auth.service.AuthTokenService;
import tech.xs.common.auth.domain.enums.AuthPathWhiteTypeEnum;
import tech.xs.common.framework.domain.annotations.AuthApi;
import tech.xs.common.framework.domain.model.ApiResult;
import tech.xs.common.framework.util.AuthHeaderUtil;
import tech.xs.common.framework.util.PermissionUtil;
import tech.xs.common.framework.util.RoleUtil;

import javax.annotation.Resource;

@Slf4j
@Validated
@RestController
@RequestMapping("/")
public class AuthController {

    @Resource
    private AuthTokenService authTokenService;

    /**
     * 退出登陆
     */
    @PostMapping("/logout")
    @AuthApi(type = AuthPathWhiteTypeEnum.ALL)
    public ApiResult<Void> logout() {
        AuthHeaderUtil.AuthHeader headToken = AuthHeaderUtil.getAuthHeader();
        if (headToken == null) {
            return ApiResult.success();
        }
        log.info("退出登陆:" + headToken);
        authTokenService.removeAuthToken(headToken.getUserId(), headToken.getClientType());
        return ApiResult.success();
    }

    /**
     * 获取当前用户拥有的所有启用的角色和权限
     */
    @GetMapping("/currJurisdiction")
    @AuthApi(type = AuthPathWhiteTypeEnum.LOGIN)
    public ApiResult<AuthUserJurisdictionBo> getCurrJurisdiction() {
        AuthUserJurisdictionBo res = new AuthUserJurisdictionBo();
        res.setPermissionCodes(PermissionUtil.getCurrUserEnablePermission());
        res.setRoleCodes(RoleUtil.getCurrUserEnableRole());
        return ApiResult.success(res);
    }

}
